package org.jetlinks.pro.assets.impl;

import org.jetlinks.pro.assets.*;
import org.springframework.beans.factory.ObjectProvider;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultAssetManager implements AssetManager {

    private final Map<String, AssetSupplier> assetSuppliers = new ConcurrentHashMap<>();

    public DefaultAssetManager(ObjectProvider<AssetSupplier> provider) {
        provider.forEach(this::register);
    }

    @Override
    public Mono<Asset> getAsset(@Nonnull AssetType assetType,
                                @Nonnull String assetId) {
        return Mono
            .justOrEmpty(assetSuppliers.get(assetType.getId()))
            .flatMap(supplier -> supplier.getAssets(assetType, Collections.singletonList(assetId)).singleOrEmpty());
    }

    @Override
    public Flux<Asset> getAssets(@Nonnull AssetType assetType,
                                 @Nonnull Collection<?> assetId) {
        return Mono
            .justOrEmpty(assetSuppliers.get(assetType.getId()))
            .flatMapMany(supplier -> supplier.getAssets(assetType, assetId));
    }

    protected void register(AssetSupplier supplier) {
        for (AssetType type : supplier.getTypes()) {
            assetSuppliers.put(type.getId(), supplier);
            AssetTypes.registerType(type);
        }
    }
}
